package com.toman.ui.work.workplan;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.lzy.okhttputils.OkHttpUtils;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseDayPlanEntity;
import com.toman.JavaBean.DeviceHouseDayPlanMappingEntity;
import com.toman.JavaBean.DeviceHouseMonthDayPlanEntity;
import com.toman.JavaBean.DeviceHouseMonthPlanEntity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DoubleMarkerView;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.NetworkUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.WaveView;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
import okhttp3.Request;
import okhttp3.Response;

public class WorkshopDayPlanActivity extends ToolBarActivity {


    DeviceHouseDayPlanEntity bean = new DeviceHouseDayPlanEntity();
    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.wv)
    WaveView wv;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.wv2)
    WaveView wv2;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.tv_title)
    LinearLayout tvTitle;
    @BindView(R.id.app_layput)
    AppBarLayout appLayput;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.nest_scrollview)
    NestedScrollView nestScrollview;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    CommonAdapter<DeviceHouseDayPlanMappingEntity> adapter;
    List<DeviceHouseDayPlanMappingEntity> list = new ArrayList<>();
    DeviceHouseMonthDayPlanEntity MonthItemBean = new DeviceHouseMonthDayPlanEntity();
    @BindView(R.id.bottom_navigation_view)
    BottomNavigationView bottomNavigationView;
    @BindView(R.id.barChart)
    BarChart barChart;
    @BindView(R.id.nest_scrollview2)
    NestedScrollView nestScrollview2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workshop_day_plan);
        ButterKnife.bind(this);
        initIntent();
        initView();
    }

    private void initIntent() {
        if (getIntent().getStringExtra("id") != null) {
            departmentId = getIntent().getStringExtra("id");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if ((boolean) SPUtils.get(getApplicationContext(), baseEnum.update(), false)) {
//            SPUtils.put(getApplicationContext(), baseEnum.update(), false);
//            customer(1, 1, "");
//        }
        if (getIntent().getSerializableExtra("entity")!=null){
            DeviceHouseDayPlanEntity entity= (DeviceHouseDayPlanEntity) getIntent().getSerializableExtra("entity");
            tvMonth.setText(entity.getDay());
            departmentId=entity.getDepartmentId()+"";
            customer(1,1,"");
        }
        else {
            customer(1,1,"");

        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_add_edit_delete, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_add);
        MenuItem menuItem1 = menu.findItem(R.id.menu_edit);
        MenuItem menuItem2 = menu.findItem(R.id.menu_delete);

        if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
        }
        if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.EDIT))) {
            menuItem1.setVisible(false);
        }
        if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.DELETE))) {
            menuItem2.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            Bundle bundle = new Bundle();

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
                        bundle.putString("id", getIntent().getStringExtra("id"));
                        bundle.putString("name", getIntent().getStringExtra("name"));
                        IntentUtils.startActivity(WorkshopDayPlanActivity.this, WorkshopDayPlanAddActivity.class, bundle);
                        break;
                    case R.id.menu_edit:
                        if (list.size() == 0) {
                            ToastUtil.makeText(getApplicationContext(), "当前工作日暂无工作计划");

                        } else {
                            bundle.putSerializable("list", (Serializable) list);
                            bundle.putSerializable("bean", bean);
                            IntentUtils.startActivity(WorkshopDayPlanActivity.this, WorkshopDayPlanEditActivity.class, bundle);
                        }
                        break;
                    case R.id.menu_delete:
                        if (list.size() == 0) {
                            ToastUtil.makeText(getApplicationContext(), "当前工作日暂无工作计划");
                        } else {
                            BaseNetUtil.actionDialog(WorkshopDayPlanActivity.this, NewBaseUrl.devicehousedayplan_delete, bean.getId() + "", token, "删除" + baseEnum.name, () -> customer(1, 1, ""));

                        }
                        break;


                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
//将月计划的日期带过来
        if (getIntent().getSerializableExtra("bean") != null) {
            MonthItemBean = (DeviceHouseMonthDayPlanEntity) getIntent().getSerializableExtra("bean");
            tvMonth.setText(MonthItemBean.getDay());
        } else {
            tvMonth.setText(TimeUtil.getNowTimeNew());
        }
//        customer(1, 1, "");
        baseEnum = BaseEnum.WORKSHOPDAYPLAN;
        initToolBar(baseEnum.name);

        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getApplicationContext())) {
                    // 如果网络可用，则加载网络数据
                    customer(1, 1, "");
                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_data:
                        ViewUtil.visible(nestScrollview, tvTitle);
                        ViewUtil.gone(nestScrollview2);


                        break;
                    case R.id.menu_chart:
                        ViewUtil.gone(nestScrollview, tvTitle);
                        ViewUtil.visible(nestScrollview2);
                        appLayput.setExpanded(true,false);


                        break;
                }
                return true;

            }
        });
        appLayput.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {
                    bgaRefresh.setPullDownRefreshEnable(true);

                } else {
                    bgaRefresh.setPullDownRefreshEnable(false);

                }
            }
        });


        initAdapter();
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
    }

    private void initAdapter() {
        adapter = new CommonAdapter<DeviceHouseDayPlanMappingEntity>(this, R.layout.item_workshop_day_plan, list) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseDayPlanMappingEntity item, final int position) {
//                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                holder.setText(R.id.tv_beltline, item.getBeltlineName());
                holder.setText(R.id.tv_plan, item.getPlanOutput() + "");
                holder.setText(R.id.tv_collect, item.getReportOutput() + "");
                holder.setText(R.id.tv_finish, item.getFinishCount() + "");
                Button button = holder.getView(R.id.btn);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("bean", item);
                        bundle.putSerializable("beanParent", bean);
                        IntentUtils.startActivity(WorkshopDayPlanActivity.this, SubmitPlanAddActivity.class, bundle);
                    }
                });

            }
        };
    }


    @OnClick(R.id.tv_month)
    public void onViewClicked() {
        onYearMonthDayPicker();
    }

    public void onYearMonthDayPicker() {
        final DatePicker picker = new DatePicker(this);
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeStart(TimeUtil.getNowYear() - 2, 1, 1);
        picker.setRangeEnd(TimeUtil.getNowYear() + 1, 12, 30);
        picker.setSelectedItem(TimeUtil.getNowYear(), TimeUtil.getNowMonth(), TimeUtil.getNowDay());
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                tvMonth.setText(year + "-" + month + "-" + day);
                customer(1, 1, "");

            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }


        OkHttpUtils
                .get(NewBaseUrl.devicehousedayplan_appselectlist)
                .params("token", token)
                .params("day", tvMonth.getText().toString())
                .params("departmentId", departmentId)

                .execute(new StringLoadingCallback(this) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", baseEnum.name + ": " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {

                            List<DeviceHouseDayPlanMappingEntity> jsonArray = new ArrayList<>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("list"), DeviceHouseDayPlanMappingEntity.class));
                            bean = JSON.parseObject(jsonObj.getString("entity"), DeviceHouseDayPlanEntity.class);
                            ;
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                            initData();


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        bgaRefresh.endRefreshing();
                    }
                });
    }

    private void initData() {
        float collect_total = 0, finish_total = 0, plan_total = 0;
        float[] collect = new float[list.size()];
        float[] finish = new float[list.size()];
        String[] belts = new String[list.size()];

        if (list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                DeviceHouseDayPlanMappingEntity bean = list.get(i);
                collect_total = collect_total + bean.getReportOutput();
                finish_total = finish_total + bean.getFinishCount();
                plan_total = plan_total + bean.getPlanOutput();
                collect[i] = bean.getReportOutput();
                finish[i] = bean.getFinishCount();
                belts[i]=bean.getBeltlineName();
            }
            tvCollect.setText((int) collect_total + "/" + (int) plan_total);
            tvFinish.setText((int) finish_total + "/" + (int) plan_total);
            int collectRate = 0, finishRate = 0;
            if (plan_total != 0) {
                collectRate = (int) ((collect_total / plan_total) * 100);
                finishRate = (int) ((finish_total / plan_total) * 100);
                wv.setProgress(collectRate);
                wv2.setProgress(finishRate);
            }
            bar(belts,collect,finish);


        } else {
            tvCollect.setText((int) 0 + "/" + (int) 0);
            tvFinish.setText((int) 0 + "/" + (int) 0);
            wv.setProgress(0);
            wv2.setProgress(0);
        }

    }
    private void initBar() {
        barChart.setDrawGridBackground(false);

        // no description text
        barChart.getDescription().setEnabled(false);

        // enable touch gestures
        barChart.setTouchEnabled(true);

        // enable scaling and dragging
        barChart.setDragEnabled(true);
        barChart.setScaleEnabled(true);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);
        barChart.getAxisRight().setEnabled(false);


        // if disabled, scaling can be done on x- and y-axis separately
        barChart.setPinchZoom(true);
        barChart.clear();
    }
    private void bar(String[] str, float[] content, float[] content2) {
        initBar();


        List<BarEntry> yVals1 = new ArrayList<>();
        for (int i = 0; i < content.length; i++) {
            yVals1.add(new BarEntry(i,content[i]));
        }

        ArrayList<BarEntry> yVals2 = new ArrayList<>();

        for (int i = 0; i < content2.length; i++) {

            yVals2.add(new BarEntry(i, content2[i]));

        }


//        int ssmax = (int) max;
        try {
            barChart.setVisibility(View.VISIBLE);

            BarDataSet set1, set2, set3;

            if (barChart.getData() != null &&
                    barChart.getData().getDataSetCount() > 0) {
                set1 = (BarDataSet) barChart.getData().getDataSetByIndex(0);
                set2 = (BarDataSet) barChart.getData().getDataSetByIndex(1);
                set1.setValues(yVals1);
                set2.setValues(yVals2);
                barChart.getData().notifyDataChanged();
                barChart.notifyDataSetChanged();
                barChart.animateXY(1000, 1000);
                barChart.getData().notifyDataChanged();

            } else {
                // create a dataset and give it a type
                set1 = new BarDataSet(yVals1, "月系统采集");

                set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                set1.setColor(getResources().getColor(R.color.line_bule));

                set1.setHighLightColor(getResources().getColor(R.color.line_bule));
                set1.setDrawValues(false);
                //set1.setFillFormatter(new MyFillFormatter(0f));
                //set1.setDrawHorizontalHighlightIndicator(false);
                //set1.setVisible(false);
                //set1.setCircleHoleColor(Color.WHITE);
                // create a dataset and give it a type
                set2 = new BarDataSet(yVals2, "月完工数量");
                set2.setAxisDependency(YAxis.AxisDependency.LEFT);
                set2.setColor(getResources().getColor(R.color.line_green));
                set2.setDrawValues(false);

                set2.setHighLightColor(Color.rgb(244, 117, 117));
                //set2.setFillFormatter(new MyFillFormatter(900f));
                XAxis xAxis = barChart.getXAxis();
                LabelFormatter labelFormatter = new LabelFormatter(str);
                xAxis.setValueFormatter(labelFormatter);
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                YAxis leftAxis = barChart.getAxisLeft();
                leftAxis.setAxisMinimum(0f);

//                横坐标粒度 缩放
                xAxis.setAxisMinimum(0f);

                xAxis.setGranularity(1f);

                if (str.length<=6){
                    xAxis.setLabelCount(str.length);
                }

                DoubleMarkerView mv = new DoubleMarkerView(this, str,content,content2);
                mv.setChartView(barChart); // For bounds control
                barChart.setMarker(mv);

                // create a data object with the datasets
                com.github.mikephil.charting.data.BarData data = new com.github.mikephil.charting.data.BarData(set1, set2);
                int barAmount =2; //需要显示柱状图的类别 数量
//设置组间距占比30% 每条柱状图宽度占比 70% /barAmount  柱状图间距占比 0%
                float groupSpace = 0.3f; //柱状图组之间的间距
                float barWidth = (1f - groupSpace) / barAmount;
                float barSpace = 0f;
//设置柱状图宽度
                data.setBarWidth(barWidth);
                data.groupBars(0f, groupSpace, barSpace);

                data.setValueTextColor(Color.BLACK);
                data.setValueTextSize(9f);

                // set data
                barChart.setData(data);
                barChart.animateXY(1000, 1000);

            }


        } catch (Exception e) {
        }
    }
    class LabelFormatter implements IAxisValueFormatter {
        private final String[] mLabels;

        public LabelFormatter(String[] labels) {
            mLabels = labels;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            try {

                return mLabels[(int) value];
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }

        }
    }

}
